# frozen_string_literal: true

module VulnerabilityFeedback
  class DestroyService < ::BaseService
    include Gitlab::Utils::StrongMemoize

    def initialize(project, user, vulnerability_feedback, revert_vulnerability_state: true, comment: nil)
      @project = project
      @current_user = user
      @vulnerability_feedback = vulnerability_feedback
      @revert_vulnerability_state = revert_vulnerability_state
      @comment = comment
    end

    def execute
      # TODO: Add system note when destroying a dismissal feedback
      raise Gitlab::Access::AccessDeniedError unless can?(current_user, :destroy_vulnerability_feedback, vulnerability_feedback)

      revert_vulnerability if revert_vulnerability_state?
      vulnerability_feedback.destroy
    end

    private

    attr_reader :vulnerability_feedback, :revert_vulnerability_state

    def revert_vulnerability
      Vulnerabilities::RevertToDetectedService.new(current_user, existing_vulnerability, @comment).execute
    end

    def revert_vulnerability_state?
      revert_vulnerability_state && existing_vulnerability
    end

    def existing_vulnerability
      strong_memoize(:existing_vulnerability) { vulnerability_feedback.finding&.vulnerability }
    end
  end
end
